import OrgTree from '@/components/OrgTree';
import SearchTablePage, { SearchTablePageRefType } from '@/components/SearchTablePage';
import { PERMISSION_KEY_USER } from '@/constants';
import { getOrgTrees } from '@/services/system/org';
import { getRoleSelectList } from '@/services/system/role';
import {
  addUser,
  addUserRole,
  deleteUserById,
  deleteUsersByIdList,
  getUserById,
  getUserList,
  getUserRole,
  resetPassword,
  updateUser,
} from '@/services/system/user';
import { checkRespSuccessful } from '@/utils/serviceUtils';
import { ModalForm, ProFormInstance, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Access, useAccess, useModel } from '@umijs/max';
import { Popconfirm, message, theme } from 'antd';
import { Key, useRef, useState } from 'react';

const User: React.FC = () => {
  const [modalOpen, setModalOpen] = useState(false);
  const modalFormRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.User>();
  const { initialState } = useModel('@@initialState');
  const access = useAccess();
  const { useToken } = theme;
  const { token } = useToken();
  const [selectOrgIdList, setSelectOrgIdList] = useState<Key[]>([]);
  const searchTablePageActionRef = useRef<SearchTablePageRefType>(null);
  return (
    <>
      <SearchTablePage<API.User>
        tableName="用户"
        getRowById={getUserById}
        updateRow={updateUser}
        addRow={addUser}
        deleteRowById={deleteUserById}
        deleteRowsByIdList={deleteUsersByIdList}
        getRowsByPage={getUserList}
        permissionKey={PERMISSION_KEY_USER}
        ref={searchTablePageActionRef}
        onReset={() => {
          setSelectOrgIdList([]);
        }}
        params={{
          orgId: selectOrgIdList?.length > 0 ? selectOrgIdList[0] : undefined,
        }}
        onAdd={() => {
          if (selectOrgIdList.length > 0) {
            setTimeout(() => {
              searchTablePageActionRef.current?.setModalFormFieldValue('orgId', selectOrgIdList[0]);
            });
          }
        }}
        columns={[
          {
            title: '用户 ID',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
            hideInModal: true,
          },
          {
            title: '用户名称',
            dataIndex: 'name',
            showDetail: true,
            rules: [{ required: true }],
          },
          {
            title: '用户昵称',
            dataIndex: 'nickName',
            hideInSearch: true,
          },
          {
            title: '所属机构',
            dataIndex: 'orgId',
            valueType: 'treeSelect',
            rules: [{ required: true }],
            allowClear: true,
            secondary: true,
            hideInSearch: true,
            request: async () => {
              const res = await getOrgTrees();
              if (checkRespSuccessful(res)) {
                return res.data || [];
              }
              return [];
            },
            fieldProps: {
              fieldNames: {
                value: 'id',
              },
            },
          },
          {
            title: '用户状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: initialState?.system_user_status?.valueEnum,
            options: initialState?.system_user_status?.numOptions,
            rules: [{ required: true, message: '请选择状态' }],
          },
          {
            title: '电话',
            dataIndex: 'phone',
            hideInSearch: true,
          },
          {
            title: '邮箱',
            dataIndex: 'email',
            hideInSearch: true,
          },
          {
            title: '备注',
            dataIndex: 'remark',
            hideInSearch: true,
            hideInTable: true,
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInSearch: true,
            hideInModal: true,
          },
        ]}
        leftSide={
          <OrgTree
            selectedKeys={selectOrgIdList}
            onSelect={(selectedKeys) => {
              setSelectOrgIdList(selectedKeys);
            }}
            checkPermission={false}
            style={{
              flex: '0 0 auto',
              minWidth: 160,
              maxWidth: 260,
              overflow: 'auto',
              backgroundColor: token.colorBgContainer,
              paddingTop: token.paddingContentHorizontalLG,
              paddingBottom: token.paddingContentHorizontalLG,
              paddingLeft: token.padding,
              paddingRight: token.padding,
              borderRadius: token.borderRadius,
              borderWidth: 1,
              borderStyle: 'solid',
              borderColor: token.colorBorderSecondary,
            }}
          />
        }
        actionRender={(text, record, nodes) => {
          return [
            <Access
              key="linkRole"
              accessible={access.permissionFilter(PERMISSION_KEY_USER.addUserRole)}
            >
              <a
                key="linkRole"
                onClick={() => {
                  setCurrentRow(record);
                  setModalOpen(true);
                }}
                type="link"
                style={{
                  flex: undefined,
                }}
              >
                关联角色
              </a>
            </Access>,
            <Access
              key="resetPassword"
              accessible={access.permissionFilter(PERMISSION_KEY_USER.resetPassword)}
            >
              <Popconfirm
                placement="topRight"
                title={`重置密码`}
                description={`是否确认重置 ${record.name} 密码，密码重置后原密码将不可使用`}
                onConfirm={() => {
                  if (record.id === undefined) {
                    message.error(`系统异常，原因为：选中删除的用户 ID 为空`);
                    return;
                  }
                  resetPassword(record.id)
                    .then((res) => {
                      if (!checkRespSuccessful(res)) {
                        message.error(`重置密码失败，后台响应：${res.message}`);
                        return;
                      }
                      message.success(`${record.name} 密码已重置，请使用初始密码登录`);
                    })
                    .catch((err) => {
                      message.error(`重置密码失败，后端系统异常`);
                      console.error(err);
                    });
                }}
              >
                <a
                  type="link"
                  style={{
                    flex: undefined,
                  }}
                >
                  重置密码
                </a>
              </Popconfirm>
            </Access>,
            ...nodes,
          ];
        }}
      />
      {modalOpen && (
        <ModalForm
          title="关联角色"
          width={600}
          layout="horizontal"
          labelCol={{ span: 5 }}
          open={modalOpen}
          omitNil
          isKeyPressSubmit
          request={async () => {
            if (currentRow && currentRow.id !== undefined) {
              const res = await getUserRole(currentRow.id);
              if (checkRespSuccessful(res)) {
                return {
                  userId: currentRow.id,
                  name: currentRow.name,
                  nickName: currentRow.nickName,
                  roleIds: res.data,
                };
              } else {
                return {
                  userId: currentRow.id,
                  name: currentRow.name,
                  nickName: currentRow.nickName,
                };
              }
            }
            return {};
          }}
          onOpenChange={setModalOpen}
          onFinish={async (values) => {
            const hide = message.loading(`正在更新用户角色`);
            try {
              const { userId, roleIds } = values;

              if (!userId) {
                message.error(`未选中任何用户，无法关联用户角色`);
                return;
              }

              const res = await addUserRole({ userId, roleIds: roleIds || [] });
              hide();
              if (checkRespSuccessful(res)) {
                message.success(`用户角色关联成功`);
                setModalOpen(false);
                setCurrentRow(undefined);
              } else {
                message.error(`用户角色关联失败，后台响应：${res.message}，请重试`);
              }
            } catch (error) {
              hide();
              message.error(`用户角色关联失败，请重试`);
            }
          }}
          formRef={modalFormRef}
        >
          <ProFormText hidden name="userId" label="用户 ID" />
          <ProFormText readonly name="name" label="用户名称" />
          <ProFormText readonly name="nickName" label="用户昵称" />
          <ProFormSelect
            name="roleIds"
            label="关联角色"
            fieldProps={{
              fieldNames: {
                value: 'id',
                label: 'name',
              },
              mode: 'multiple',
            }}
            request={async () => {
              const res = await getRoleSelectList();
              if (checkRespSuccessful(res)) {
                return res.data || [];
              }
              return [];
            }}
            placeholder="请选择"
          />
        </ModalForm>
      )}
    </>
  );
};

export default User;
